<template>
	<view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
		<view class="content detail">
		<uni-forms err-show-type="toast" ref="formRef" :model="formData" labelWidth="80px">
			<!--采购单信息-->
			<!--采购单信息-->
			<view class="detail-item">
				<uni-section title="采购单信息" type="line"></uni-section>
				<view class="detail-content">
					<view class="detail-text">
						采购单号：
						<text>{{info.number}}</text>
					</view>
					<view class="detail-text">
						仓库名称：
						<text>{{info.warehouseName}}</text></view>
					<view class="detail-text">
						采购人员：
						<text>{{info.purchaseUserName}}</text></view>
					<view class="detail-text">
						供应商：
						<text>{{info.supplierName}}</text></view>
					<view class="detail-text">
						下单时间：
						<text>{{info.createTime}}</text></view>
					<view class="detail-text">
						仓库地址：
						<text>{{warehouseInfo.addr}}</text></view>
					<view class="detail-text" v-if="checkPermi(['zhouyz:purchaseOrder:price'])">
						采购金额：
						<text>{{info.allPrice}}</text></view>
				</view>
			</view>
			
			<!--商品清单-->
			<view class="detail-item">
				<view class="main-flex">
					<uni-section title="商品清单" type="line"></uni-section>
					<!--操作-->
					<view class="operate main-flex">
						<up-button
							class="operate-btn main-flex"
							size="mini"
							type="primary"
							@click="addFun">
							<uni-icons class="operate-btn-icon" type="loop" size="28rpx" color="#ffffff"></uni-icons>
							<view class="operate-btn-text">变更最新价</view>
						</up-button>
					</view>
				</view>
				<view class="detail-content table">
					<ty-table
						:data="chooseProductList"
						:columns="columns"
						:sortable="true"
						:cellClassName="() => 'table-cell'"
						:headerCellClassName="() => 'table-cell'"
						:rowClassName="() => 'table-row'"
						stripe
						border>
						<template v-slot:table1="{ row }">
							<view class="table-td-cell">
								<view class="table-td-row main-flex" style="overflow: hidden;">
									商品：
									<text class="table-td-text main-flex-item">{{row.productName}}</text>
								</view>
								<view class="table-td-row main-flex">
									单位：
									<text class="table-td-text main-flex-item">{{row.unit}}</text>
								</view>
								<view class="table-td-row main-flex">
									采购价：
									<text class="table-td-text price">￥{{row.purchasePrice}}</text>
								</view>
								<view class="table-td-row main-flex">
									最新采购价：
									<text class="table-td-text price">￥{{row.newPurchasePrice}}</text>
								</view>
							</view>
						</template>
						<template v-slot:table2="{ row }">
							<view class="table-td-cell">
								<view class="table-td-row main-flex">
									数量：
									<view class="table-td-input">
										<uni-number-box @change="changePurchaseNumber($event, row)" background="#007aff" color="#ffffff" v-model="row.purchaseNumber" ></uni-number-box>
									</view>
								</view>
								<view class="table-td-row main-flex">
									合计：
									<text class="table-td-text price">￥{{row.purchaseMoney}}</text>
								</view>
							</view>
						</template>
						
						<!-- <template v-slot:table3="{ row }">
							<view class="table-td-cell">
								<view class="table-td-row main-flex">
									<up-button
										class="operate-btn main-flex"
										size="mini"
										type="primary"
										@click="searchFun(row)">
										<uni-icons class="operate-btn-icon" type="search" size="28rpx" color="#ffffff"></uni-icons>
										<view class="operate-btn-text">库存</view>
									</up-button>
								</view>
								<view class="table-td-row main-flex">
									<up-button
										class="operate-btn main-flex"
										size="mini"
										type="error"
										@click="delFun(row)">
										<uni-icons class="operate-btn-icon" type="trash" size="28rpx" color="#ffffff"></uni-icons>
										<view class="operate-btn-text">删除</view>
									</up-button>
								</view>
							</view>
						</template> -->
						<template v-slot:empty>
							<view class="table-empty">
								<up-empty mode="data"/>
							</view>
						</template>
					</ty-table>
				</view>
				
				<uni-section title="采购单金额" type="line"></uni-section>
				<view class="detail-content formRef">
					<!-- <uni-forms-item label="采购总金额" name="allPrice">
						<uni-easyinput type="number" disabled v-model="formData.allPrice" placeholder="请输入采购总金额" />
					</uni-forms-item> -->
					<uni-forms-item label="采购说明" name="remark">
						<uni-easyinput type="textarea" v-model="formData.remark" placeholder="请输入采购说明"></uni-easyinput>
					</uni-forms-item>
				</view>
				
			</view>
			
			<view class="formRef-btn">
				<button type="primary" :disabled="isSubmit" :loading="isSubmit" @click="submit">提交</button>
			</view>
			</uni-forms>
		</view>
		
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref, watch } from 'vue';
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import useUserStore from '@/store/modules/user'
import { timeFormat } from 'uview-plus'
import { purchaseOrderNewPrice, purchaseOrderUpdateProducts } from "@/api/erp_api/purchase"
import { warehouseDetail } from "@/api/erp_api/warehouse"
import useSetStore from '@/store/modules/set'
import { Decimal } from 'decimal.js'

	const userStore = useUserStore()
	const setStore = useSetStore()
	const id = ref('')
	onLoad((option) => {
		if (option.id) {
			id.value = option.id
			getPurchaseOrderDetail()
		}
	})
	
	
	// 获取采购单商品
	const info = ref({})
	const getPurchaseOrderDetail = () => {
		purchaseOrderNewPrice({
			id: id.value
		}).then(res => {
			info.value = res?.data || {}
			formData.value.remark = res?.data?.remark || ''
			chooseProductList.value = res?.detail.map(item => {
				return {
					...item,
					purchaseMoney: purchaseMoney(item.purchasePrice || 0, item.purchaseNumber)
				}
			}) || []
			if (res?.data?.warehouseId) {
				getWarehouse(res.data.warehouseId)
			}
		})
	}
	const warehouseInfo = ref({})
	const getWarehouse = (warehouseId) => {
		warehouseDetail({
			id: warehouseId
		}).then(res => {
			warehouseInfo.value = res.data
		})
	}
	
	// 采购的商品
	const chooseProductList = ref([])
	// 表格头部
	const columns = ref([
		{ title: '商品信息', key: 'table1' },
		{ title: '价格信息', key: 'table2', width: '140px' },
		// { title: '操作', key: 'table3', width: '60px' }
	])
	
	const changePurchaseNumber = (e, row) => {
		chooseProductList.value[row.rowIndex].purchaseNumber = e
		const money = purchaseMoney(chooseProductList.value[row.rowIndex].purchasePrice, e)
		chooseProductList.value[row.rowIndex].purchaseMoney = money
		chooseProductList.value[row.rowIndex].subtotal = money
	}
	const purchaseMoney = (purchasePrice, purchaseNumber) => {
		return purchasePrice && purchaseNumber ? Decimal(purchaseNumber).mul(Decimal(purchasePrice)).toNumber() : 0
	}
	
	const addFun = () => {
		chooseProductList.value = chooseProductList.value.map(item => {
			const money = purchaseMoney(item.newPurchasePrice || 0, item.purchaseNumber)
			return {
				...item,
				purchasePrice: item.newPurchasePrice,
				subtotal: money,
				purchaseMoney: money
			}
		})
	}
	
	// form表单数据
	const formData = ref({
		remark: ''
	})
	const formRef = ref(null)
	const isSubmit = ref(false)
	// 提交
	const submit = () => {
		formRef.value.validate().then(formRes => {
			const allProductList = chooseProductList.value
			if (allProductList.length === 0) {
				return uni.$u.toast('商品不能为空')
			}
			const params = { 
				id: `${id.value}?remark=${formRes.remark}`
			}
			isSubmit.value = true
			purchaseOrderUpdateProducts(params, allProductList).then(async (res) => {
				modal.showToast(res.msg)
				await uni.$u.sleep(1000)
				isSubmit.value = false
				clear()
				uni.$emit('refreshList');  // 触发刷新事件
				uni.navigateBack({
					delta: 1
				})
			}).catch(err => {
				isSubmit.value = false
			})
		})
	}
	// 清空
	const clear = () => {
		formData.value = {
			remark: ''
		}
	}
	
	watch(() => chooseProductList.value, (nval, oval) => {
		totalMoney()
	},{ deep: true })
	
	// 计算总金额
	const totalMoney = () => {
		const goodsMoney = chooseProductList.value.reduce((prev, cur, index, arr) => {
			return Decimal(prev).add(cur.purchaseMoney).toNumber()
		}, 0)
		info.value.allPrice = Decimal(goodsMoney).add(Decimal(info.value?.otherPrice || 0)).sub(Decimal(info.value?.discountPrice || 0)).toNumber()
	}
</script>

<style scoped lang="scss">
	.search {
		margin-top: 0;
	}
	.table-td-input {
	}
	.price {
		font-size: 28rpx;
	}
	.operate {
		margin-left: auto;
	}
	:deep(.table-cell) {
		&:last-child {
			align-self: center;
		}
	}
	.formRef-btn {
		padding: 0rpx 20rpx 40rpx;
	}
</style>
